package user

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"zhuandan/data_source"
	"zhuandan/models"
)

type FapiaolistRBody struct {
	Data       []models.Fapiao `json:"data"`
	PageNo     int             `json:"pageNo"`
	PageSize   int             `json:"pageSize"`
	TotalCount int64           `json:"totalCount"`
	TotalPage  int64           `json:"totalPage"`
}

func Fapiaolist(ctx *gin.Context) {
	request := FankuilistBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	status := request.Status
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	var users []models.Fapiao
	res := data_source.Db.Where("uid = ?", uid)

	if status > 0 {
		res = res.Where("status = ?", status)
	}

	res.Model(&models.Fapiao{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("id desc").Find(&users)
	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := FapiaolistRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

type FapiaoaddBody struct {
	ID      int64   `json:"id" gorm:"id"`
	Uid     int64   `json:"uid" gorm:"uid"`
	Price   float64 `json:"price" gorm:"price"`
	Images  string  `json:"images" gorm:"images"`
	Addtime int64   `json:"addtime" gorm:"addtime"`
	Status  int64   `json:"status" gorm:"status"` // 1申请中 2同意 3拒绝
	URL     string  `json:"url" gorm:"url"`
	Title   string  `json:"title" gorm:"title"`
}

func Fapiaoadd(ctx *gin.Context) {
	request := FapiaoaddBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	price := request.Price
	images := request.Images

	if uid == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    300,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "请传递uid",
		})
		return
	}

	fk := models.Fapiao{
		Uid:     uid,
		Price:   price,
		Images:  images,
		Addtime: time.Now().Unix(),
		Status:  1,
	}
	data_source.Db.Create(&fk)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return

}
